import { ref, computed } from 'vue'
import type { Opening, OpeningMove, OpeningRecommendation, PlayerOpeningStats } from '../types/opening'

export function useOpeningRecommender() {
  const openingDatabase = ref<Opening[]>([
    {
      name: "Ruy Lopez",
      code: "C60",
      moves: ["e4", "e5", "Nf3", "Nc6", "Bb5"],
      evaluation: 0.3,
      popularity: 0.85,
      winRate: 0.52,
      complexity: "intermediate",
      style: "positional",
      description: "西班牙开局是最古老和最受欢迎的国际象棋开局之一。它以攻击黑方的e5兵为特点，同时为白方建立稳固的中心控制。",
      keyPositions: [
        "基本位置：白方在第三步将象移至b5格",
        "交换变例：白方在第六步用象吃掉c6马",
        "封闭变例：黑方选择...a6 Bb3 b5"
      ],
      commonPlans: [
        "控制中心",
        "攻击黑方e5兵",
        "在王翼展开攻势"
      ],
      typicalTactics: [
        "c3-d4的突破",
        "f4的推进",
        "在c文件上的车压制"
      ]
    },
    // ... 更多开��数据
  ])

  const playerStats = ref<PlayerOpeningStats[]>([])

  // 根据玩家水平和风格推荐开局
  const recommendOpening = (
    playerRating: number,
    playerStyle: 'positional' | 'tactical' | 'dynamic',
    recentMoves: string[]
  ): OpeningRecommendation[] => {
    const recommendations: OpeningRecommendation[] = []

    // 根据当前局面筛选可能的开局
    const possibleOpenings = openingDatabase.value.filter(opening => {
      const moveCount = recentMoves.length
      return opening.moves.slice(0, moveCount).every((move, i) => move === recentMoves[i])
    })

    // 为每个可能的开局计算推荐分数
    possibleOpenings.forEach(opening => {
      let confidence = 0

      // 根据玩家等级调整
      if (playerRating < 1500 && opening.complexity === 'basic') confidence += 0.3
      else if (playerRating >= 1500 && playerRating < 2000 && opening.complexity === 'intermediate') confidence += 0.3
      else if (playerRating >= 2000 && opening.complexity === 'advanced') confidence += 0.3

      // 根据玩家风格调整
      if (opening.style === playerStyle) confidence += 0.2

      // 根据开局统计调整
      const stats = playerStats.value.find(s => s.openingCode === opening.code)
      if (stats) {
        const winRate = stats.wins / (stats.wins + stats.losses + stats.draws)
        if (winRate > 0.5) confidence += 0.2
      }

      // 根据开局流行度调整
      confidence += opening.popularity * 0.1

      recommendations.push({
        opening,
        confidence,
        reason: generateRecommendationReason(opening, playerRating, playerStyle),
        alternativeMoves: getAlternativeMoves(opening, recentMoves)
      })
    })

    // 按推荐度排序
    return recommendations.sort((a, b) => b.confidence - a.confidence)
  }

  // 生成推荐理由
  const generateRecommendationReason = (
    opening: Opening,
    playerRating: number,
    playerStyle: string
  ): string => {
    const reasons: string[] = []

    if (opening.complexity === 'basic' && playerRating < 1500) {
      reasons.push('这个开局适合初学者，容易掌握基本原则')
    } else if (opening.complexity === 'intermediate' && playerRating >= 1500) {
      reasons.push('这个开局能帮助你提升战术理解')
    }

    if (opening.style === playerStyle) {
      reasons.push(`这个开局符合你的${playerStyle === 'positional' ? '位置' : playerStyle === 'tactical' ? '战术' : '动态'}风格`)
    }

    const stats = playerStats.value.find(s => s.openingCode === opening.code)
    if (stats && stats.gamesPlayed > 0) {
      const winRate = (stats.wins / stats.gamesPlayed * 100).toFixed(1)
      reasons.push(`你在这个开局中的胜率为${winRate}%`)
    }

    return reasons.join('。')
  }

  // 获取替代走法
  const getAlternativeMoves = (
    opening: Opening,
    currentMoves: string[]
  ): OpeningMove[] => {
    const moveIndex = currentMoves.length
    const alternatives: OpeningMove[] = []

    openingDatabase.value.forEach(otherOpening => {
      if (otherOpening.moves.length > moveIndex &&
          otherOpening.moves.slice(0, moveIndex).every((m, i) => m === currentMoves[i])) {
        const move = otherOpening.moves[moveIndex]
        if (!alternatives.some(alt => alt.move === move)) {
          alternatives.push({
            move,
            evaluation: otherOpening.evaluation,
            popularity: otherOpening.popularity,
            winRate: otherOpening.winRate
          })
        }
      }
    })

    return alternatives.sort((a, b) => b.popularity - a.popularity)
  }

  // 更新玩家开局统计
  const updateOpeningStats = (
    openingCode: string,
    result: 'win' | 'loss' | 'draw',
    evaluation: number
  ) => {
    const stats = playerStats.value.find(s => s.openingCode === openingCode)
    if (stats) {
      stats.gamesPlayed++
      if (result === 'win') stats.wins++
      else if (result === 'loss') stats.losses++
      else stats.draws++
      
      stats.averageEvaluation = (stats.averageEvaluation * (stats.gamesPlayed - 1) + evaluation) / stats.gamesPlayed
      stats.lastPlayed = new Date()
    } else {
      playerStats.value.push({
        openingCode,
        gamesPlayed: 1,
        wins: result === 'win' ? 1 : 0,
        losses: result === 'loss' ? 1 : 0,
        draws: result === 'draw' ? 1 : 0,
        averageEvaluation: evaluation,
        lastPlayed: new Date()
      })
    }
  }

  return {
    recommendOpening,
    updateOpeningStats,
    playerStats
  }
} 